const db = require('../Mysql/sql')
const dayjs = require('dayjs')

const lives = {
	//获取直播列表
	getLivesList(req, res) {
		let body = req.body
		const sql = `SELECT l.*,u.username,u.handimg FROM lives l,users u where l.userid = u.userid 
		${body.type?'and l.type=?':''}
		${body.like?'and l.title like "%${body.like}%" or u.username like "%${body.like}%"':''}
		`
		db.query(sql, body.type, (err, results) => {
			if (err) return res.cc(err)
			res.cc('获取成功', 200, results)
		})
	},
	//创建直播
	createLive(req, res) {
		let body = {
			userid: req.auth.userid,
			...req.body,
			createtime: dayjs().format('YYYY-MM-DD HH:mm:ss')
		}
		console.log(body)
		const sql = `insert into lives set ?`
		db.query(sql, body, (err, results) => {
			if (err) return res.cc(err)
			if (!results.affectedRows) return res.cc('创建失败')
			res.cc('创建成功', 200, results.insertId)
		})
	},
	//判断是否已开启直播
	judgeIsOpen(req, res) {
		const sql = `select * from lives where userid = ${req.auth.userid}`
		db.query(sql, [], (err, results) => {
			if (err) return res.cc(err)
			res.cc('获取成功', 200, results.length ? true : false)
		})
	},
	//结束直播
	finishLive(req, res) {
		let body = req.body
		const sql = `delete from lives where id=? and userid=${req.auth.userid}`
		db.query(sql, body.id, (err, results) => {
			if (err) return res.cc(err)
			res.cc('结束成功', 200)
		})
	},
	//修改直播信息
	reviseLive(req, res) {
		let body = req.body
		const sql = `select lives set ? where id=?`
		db.query(sql, [body, body.id], (err, results) => {
			if (err) return res.cc(err)
			res.cc('更新成功', 200)
		})
	}
}

module.exports = lives